namespace :db do
  desc "Pull down the WordPress database"
  task :pull do
    file = "#{SecureRandom.hex(8)}.sql"
    
    local_path = File.join(Dir.pwd, file)
    remote_path = File.join(fetch(:tmp_dir), file)
    
    unless fetch(:confirm_pull_database)
      set :confirm_pull_database, ask("confirmation for local database overwrite", "Y/n")
    end
    
    next unless true == fetch(:confirm_pull_database) or ["y", "yes"].include? fetch(:confirm_pull_database).downcase
    
    on roles(:app) do |server|
      info "Pulling WordPress database from #{server.user}@#{server.hostname}"
      
      within release_path do
        execute :wp, :db, :export, remote_path
      end
      
      download! remote_path, local_path
      
      execute :rm, "-f", remote_path
    end
    
    run_locally do
      execute :wp, :db, :import, local_path
      execute :rm, "-f", local_path
      
      if fetch(:local_site_url) and fetch(:site_url)
        execute :wp, "search-replace", fetch(:site_url), fetch(:local_site_url)
      end
    end
  end
end
